package com.paradogs.gs.modules.attr;

import com.paradogs.gs.misc.DBSingleRowManager;
import com.paradogs.gs.misc.annotations.GameManager;
import com.paradogs.gs.db.Attr;
import com.paradogs.gs.modules.attr.dao.AttrDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author: yumi
 * @date: 2024/11/21  22:50
 * @Description: 属性管理
 */
@Slf4j
@GameManager
public class AttrMgr extends DBSingleRowManager<AttrDao, Attr> {

    private Map<AttrBonus, IAttrCalculate> attrCalculate = new LinkedHashMap<>();

    @Autowired
    private AttrService attrService;

    @Override
    public void onInitialization(Attr data) {}

    @Override
    public void Start() {
        this.reCalAttr();
    }

    public void on(AttrBonus bonus, IAttrCalculate calculate) {
        attrCalculate.put(bonus, calculate);
    }

    /** 计算并更新属性 */
    public void reCalAttr() {
        // 汇总加成属性
        Attr attr = new Attr();
        attr.setCurHp(__raw__().getCurHp());
        attr.setCurMp(__raw__().getCurMp());
        for (IAttrCalculate calculate : attrCalculate.values()) {
            calculate.onCal1().forEach((k, v) -> attr.getAttrs().merge(k.id(), v, Integer::sum));
            log.info("Attr: {}", calculate.onCal1());
        }
        for (IAttrCalculate calculate : attrCalculate.values()) {
            calculate.onCal2().forEach((k, v) -> attr.getAttrs().merge(k.id(), v, Integer::sum));
        }
        for (IAttrCalculate calculate : attrCalculate.values()) {
            calculate.onCal3().forEach((k, v) -> attr.getAttrs().merge(k.id(), v, Integer::sum));
        }
        // 计算最终属性
        attr.setFinalAttr(attrService.calFinalAttr(attr.getAttrs()));
        __update__(attr);
    }

    public Integer getFinalAttrVal(FinalAttrType attrType) {
        return __raw__().getFinalAttr().get(attrType.id());
    }

    public Integer getAttrVal(AttrType attrType) {
        return __raw__().getAttrs().get(attrType.id());
    }

    public Integer changeHp(int change) {
        Integer val = __raw__().getCurHp() + change;
        __raw__().setCurHp(val);
        return val;
    }

    public Integer hp() {
        return __raw__().getCurHp();
    }

    public void toMaxHp() {
        __raw__().setCurHp(getFinalAttrVal(FinalAttrType.MAX_HP));
    }
}
